package com.example.demo.config;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.demo.auth.AuthConstants;
import com.example.demo.auth.AuthTokenAnno;
import com.example.demo.auth.TokenUtil;
import com.example.demo.dao.mapper.SysSessionMapper;
import com.example.demo.dao.model.SysSession;
import com.example.demo.dao.model.SysToken;
import com.example.demo.service.ITokenService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private SysSessionMapper sysSessionMapper;

    @Autowired
    private ITokenService tokenService;

    public static Map<String, String> blackList = new ConcurrentHashMap<>();

    private static final Logger logger = LoggerFactory.getLogger(AuthenticationInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        long startTime = System.currentTimeMillis();
        request.setAttribute("startTime", startTime);
        String token = request.getHeader("token");
        if(!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        Class<?> clazz = handlerMethod.getBeanType();
        System.out.println(method.getName() + " START");

        if(clazz.isAnnotationPresent(AuthTokenAnno.class)) {
            AuthTokenAnno parAnno = clazz.getAnnotation(AuthTokenAnno.class);
            AuthTokenAnno mthAnno = method.getAnnotation(AuthTokenAnno.class);

            if(mthAnno.required()) {
                verifyToken(mthAnno, token, request);
            } else if(parAnno.required()) {
                verifyToken(parAnno, token, request);
            } else  {
                logger.info(String.format("Request Path is %s, no need to validate token, let it go.", request.getRequestURI()));
            }

        } else if(method.isAnnotationPresent(AuthTokenAnno.class)) {
            AuthTokenAnno mthAnno = method.getAnnotation(AuthTokenAnno.class);
            if(mthAnno.required()) {
                verifyToken(mthAnno, token, request);
            } else {
                logger.info(String.format("Request Path is %s, no need to validate token, let it go.", request.getRequestURI()));
            }

        }

        return true;
    }

    private void verifyRoles(AuthTokenAnno tokenAnno, List<String> roles) {
        String role = tokenAnno.role();
        if(StringUtils.isNotEmpty(role)) {
            roles.add(role);
        }
        String roleArr[] = tokenAnno.roles();
        if(roleArr != null && roleArr.length > 0) {
            roles.addAll(Arrays.asList(roleArr));
        }

    }

    private void verifyToken(AuthTokenAnno tokenAnno, String token, HttpServletRequest request) {
        // do authentication
        if(StringUtils.isEmpty(token)) {
            logger.error("401-->Access denied, please login first.");
            throw new RuntimeException("401-->Access denied, please login first.");
        }

        String sessionId;
        String tokenId;
        try {
            DecodedJWT dt = JWT.decode(token);
            sessionId = dt.getAudience().get(0);
            tokenId =dt.getAudience().get(1);
        } catch (JWTDecodeException j) {
            logger.error("401-->token is invalid.");
            throw new RuntimeException("401-->token is invalid.");
        }

        // get session id from db
        SysSession session = this.sysSessionMapper.selectByPrimaryKey(sessionId);
        if(session == null) {
            logger.error("401-->session id is invalid.");
            throw new RuntimeException("401-->session id is invalid.");
        }

        Date expDate = session.getExpireTime();
        if(expDate != null) {
            long now = System.currentTimeMillis();
            if(now >= expDate.getTime()) {
                logger.error("401-->session timeout.");
                throw new RuntimeException("401-->session timeout.");
            }
        }

        if(!TokenUtil.validateToken(token, AuthConstants.SECRET_TOKEN_KEY)) {
            logger.error("401-->token is invalid.");
            throw new RuntimeException("401-->token is invalid.");
        }

        // black list check
        SysToken sysToken = this.tokenService.selectOne(tokenId);

        if(StringUtils.equals(token, sysToken.getToken())) {
            throw new RuntimeException("401-->token is in black list, please login again.");
        }

        logger.info(String.format("Request Path is %s, token validation is okay, let it go.", request.getRequestURI()));

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if(!(handler instanceof HandlerMethod)) {
            return;
        }
        long endTime = System.currentTimeMillis();
        long startTime = (long) request.getAttribute("startTime");

        double consumedTime = (endTime - startTime) / 1000d;
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        System.out.println(method.getName() + " END, time consumed: " + consumedTime + " secs.");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
